export function useViewSort(itemHeight: number, initValue: any[]) {
  const { ctx } = getCurrentInstance()
  const movableContainerHeight = ref(0)
  const list = ref<SortItem[]>([])
  const activeIndex = ref(-1)
  const moveToIndex = ref(-1)
  const oldIndex = ref(-1)
  const cloneList = ref([])
  interface SortItem {
    name: string
    price: string
    img: string
    key?: string | number
    y?: number
  }
  onLoad(() => {
    initList(initValue)
  })

  onReady(() => {
    ctx.$uv.getRect('.movable-container').then((res) => {
      movableContainerHeight.value =
        res.height > initValue.length * itemHeight ? res.height : initValue.length * itemHeight
    })
  })
  function initList(val: SortItem[]) {
    list.value = JSON.parse(JSON.stringify(val)).map((item: any, index: number) => {
      return {
        ...item,
        y: index * itemHeight,
        key: Math.random() + index,
      }
    })
    cloneList.value = JSON.parse(JSON.stringify(list.value))
  }
  function handleDragStart(index: number) {
    activeIndex.value = index
    oldIndex.value = index
  }

  function handleMoving(e: any) {
    if (e.detail.source !== 'touch') return
    const { y } = e.detail
    const currentY = Math.floor((y + itemHeight / 2) / itemHeight)
    moveToIndex.value = Math.min(currentY, list.value.length - 1)
    if (oldIndex.value !== moveToIndex.value && oldIndex.value !== -1 && moveToIndex.value !== -1) {
      const newList = JSON.parse(JSON.stringify(list.value))
      // 交换位置
      newList.splice(moveToIndex.value, 0, ...newList.splice(activeIndex.value, 1))
      list.value.forEach((item: any, index: number) => {
        if (index !== activeIndex.value) {
          const itemIndex = newList.findIndex((val: SortItem) => val.key === item.key)
          item.y = itemIndex * itemHeight
        }
      })
    }
  }

  function handleDragEnd() {
    if (
      moveToIndex.value !== -1 &&
      activeIndex.value !== moveToIndex.value &&
      activeIndex.value !== -1
    ) {
      cloneList.value.splice(moveToIndex.value, 0, ...cloneList.value.splice(activeIndex.value, 1))
    }
    initList(cloneList.value)
    activeIndex.value = -1
    moveToIndex.value = -1
    oldIndex.value = -1
  }

  return {
    movableContainerHeight,
    list,
    activeIndex,
    moveToIndex,
    itemHeight,
    oldIndex,
    cloneList,
    handleDragStart,
    handleMoving,
    handleDragEnd,
  }
}
